// Android APP
(function () {
  function isAndroid() {
    return /(Android)/i.test(navigator.userAgent);
  }

  try {
    if (!isAndroid() || !Android) return;
  } catch (e) {
    console.error(e);
    return;
  }

  const nav = document.getElementsByTagName("nav")[0];
  const ul = nav ? nav.getElementsByTagName("ul")[0] : undefined;
  if (ul) {
    ul.innerHTML += `
    <li>
      <a href="/pages/admin-varlet/login.html">后台</a>
    </li>
  `;
  }

  const aDownloadElements = document.querySelectorAll("a[download]");
  for (let index = 0; index < aDownloadElements.length; index++) {
    /** @type { HTMLAnchorElement } */
    const element = aDownloadElements[index];
    let url = element.href;
    const fileName = element.download;
    if (!url.includes("http") && url[0] === "/") {
      url = window.location.protocol + "//" + window.location.hostname + url;
    }
    element.target = "_self";
    element.href = "";
    element.setAttribute(
      "onclick",
      `AndroidUtil.download("${url}", "${fileName}")`,
    );
  }

  // Share
  window.navigator.share = (options) => {
    let text = `<a href="${options.url}">`;
    if (options.text) text += options.text;
    text += "</a>";
    Android.shareText(text);
  };

  // 发送邮件
  const aElements = document.querySelectorAll("a[href]");
  for (let index = 0; index < aElements.length; index++) {
    const element = aElements[index];
    if (element.href.includes("mailto")) {
      const target = decodeURI(
        element.href.match(/mailto:\s*([^@]*@[^,\?]*)?/)[1],
      );
      const subject = decodeURI(element.href.match(/subject=([^&]*)/)[1]);
      element.setAttribute(
        "onclick",
        `Android.sendEmail('${target}', '${subject}', '')`,
      );
      element.href = "#";
    }
  }

  // RSS
  const rssImageElement = document.querySelector("img[alt=RSS]");
  if (rssImageElement) {
    rssImageElement.setAttribute(
      "onclick",
      `DialogX.message('RSS订阅源', '${window.location.protocol}//${window.location.hostname}/rss')`,
    );
  }

  // 判断新版本（已在应用程序内实现）
  // const currentVersion = Android.getVersion();
  // fetch("/api/android/version", { method: "GET" })
  // .then(response => response.json())
  // .then((result) => {
  //     const versionInfo = result.data;
  //     if (currentVersion !== versionInfo.newestVersion)
  //     {
  //         const versionCode = versionInfo.version[versionInfo.newestVersion];
  //         const fileName = `鸽子分享网-${versionInfo.newestVersion}.apk`;
  //         window.onJsBridgeReady = () => {
  //             JsBridge.DialogX.message(
  //                 "更新",
  //                 "是否下载最新版本？",
  //                 function() {
  //                     JsBridge.Util.downloadFile(
  //                         `http://android.cyue.net/${versionCode}.apk`,
  //                         fileName,
  //                         function() {
  //                             DialogX.tip(fileName + "下载完成！", "success")
  //                         }
  //                     );
  //                 }
  //             )
  //         }
  //     }
  // });
})();

var AndroidUtil = {
  download(url, fileName) {
    if (!JsBridge) return;
    JsBridge.DialogX.message("提示", "是否下载“" + fileName + "”", function () {
      JsBridge.Util.downloadFile(url, fileName, function () {
        DialogX.tip(fileName + "下载完成！", "success");
      });
    });
  },

  openAlbum() {
    return new Promise((resolve) => {
      JsBridge.Util.openAlbum(function (uriString) {
        const imgData = JsBridge.Util.readFileByUriToBase64(uriString);
        resolve("data:image/png;base64," + imgData);
      });
    });
  },
};
